package com.xinzhi.service.impl;

import com.xinzhi.mapper.LoanInterestMapper;
import com.xinzhi.pojo.LoanInterest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Service
public class LoanInterestService {

    @Autowired
    private LoanInterestMapper loanInterestMapper;

    public List<LoanInterest> getAllLoanInterests() {
        return loanInterestMapper.selectAllLoanInterests();
    }

    public LoanInterest getLoanInterestById(Integer id) {
        return loanInterestMapper.selectLoanInterestById(id);
    }

    public void createLoanInterest(LoanInterest loanInterest) {
        loanInterestMapper.insert(loanInterest);
    }

    public void updateLoanInterest(LoanInterest loanInterest) {
        loanInterestMapper.updateLoanInterest(loanInterest);
    }

    public void deleteLoanInterest(Integer id) {
        loanInterestMapper.deleteLoanInterest(id);
    }

    // 计算并保存贷款利息记录
    public void calculateAndSaveLoanInterest(LoanInterest loanInterest) {
        BigDecimal interestAmount = calculateInterest(loanInterest);
        loanInterest.setInterestAmount(interestAmount);
        loanInterest.setInterestProcessingDate(new Date());
        loanInterest.setInterestProcessingFlag('1'); // 已处理标志

        loanInterestMapper.insert(loanInterest); // 保存贷款利息记录
    }

    // 计算贷款利息
    BigDecimal calculateInterest(LoanInterest loanInterest) {
        BigDecimal loanBalance = loanInterest.getLoanBalance();
        BigDecimal interestRate = BigDecimal.valueOf(loanInterest.getInterestRate());
        long days = calculateDaysBetweenDates(loanInterest.getInterestStartDate(), loanInterest.getInterestDueDate());

        BigDecimal interestAmount = loanBalance
                .multiply(BigDecimal.valueOf(days))
                .multiply(interestRate)
                .divide(BigDecimal.valueOf(365), 2, BigDecimal.ROUND_HALF_UP);

        return interestAmount;
    }

    // 计算两个日期之间的天数
    private long calculateDaysBetweenDates(Date startDate, Date endDate) {
        long diff = endDate.getTime() - startDate.getTime();
        return diff / (24 * 60 * 60 * 1000); // 将毫秒转换为天数
    }

    public List<LoanInterest> getLoanInterestsByLoanAccount(String loanAccount) {
        return loanInterestMapper.getLoanInterestsByLoanAccount(loanAccount);
    }
}
